﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using cludg.Infrastructure.DI;

namespace cludg.Web.Core.ControllerFactory
{
	public class BaseControllerFactory : DefaultControllerFactory
	{
		protected readonly IControllerRegistry ControllerRegistry;
		protected readonly IDIContainer Container;

		public BaseControllerFactory(
			IControllerRegistry controllerRegistry,
			IDIContainer container)
		{
			ControllerRegistry = controllerRegistry;
			Container = container;
		}

		protected override Type GetControllerType(RequestContext requestContext, string controllerName)
		{
			return ControllerRegistry.Get(controllerName) ?? base.GetControllerType(requestContext, controllerName);
		}

		public override IController CreateController(RequestContext requestContext, string controllerName)
		{
			var controller = base.CreateController(requestContext, controllerName);
			if (controller is Controller)
			{
				((Controller) controller).ActionInvoker = Container.Resolve<ControllerActionInvoker>();				
			}
			return controller;
		}
	}
}
